/*
 *  ptclSendData.cpp
 *  serialExample
 *
 *  Created by Motoi Ishibashi on 11/02/27.
 *  Copyright 2011 __MyCompanyName__. All rights reserved.
 *
 */

#include "ptclSendData.h"

ptclSendData::ptclSendData()
{
	serial = NULL;
	pixelBuff = new unsigned char[PIXELSIZE*CHECKPOINTNUM];
	for(int i=0; i<PIXELSIZE*CHECKPOINTNUM; i++){
		pixelBuff[i] = 0;
	}
	pixelSubBuff = new unsigned char[PIXELSUBSIZE];
	colorlAlternatedPixels = new unsigned char[PIXELSIZE*CHECKPOINTNUM*3];
	bLoop = false;
}

ptclSendData::~ptclSendData()
{
	delete pixelBuff;
}

void ptclSendData::threadedFunction()
{
	while (bLoop) {
		
		cout << "ok" << endl;
		
		for (int i=0; i<CHECKPOINTNUM; i++) {
			for (int j=0; j<PIXELSUMNUM; j++) {
				
				for (int k=0; k<PIXELSUBSIZE; k++) {
					pixelSubBuff[k] = pixelBuff[PIXELSIZE*i + PIXELSUBSIZE*j + k];
				}
				serial->writeByte(0xFF);
				serial->writeByte(0xA1);
				unsigned char h = (unsigned char)((unsigned char)(i<<4) | j);
				
				if (i==0&&j==0) {
					cout << "pixelSubBuff[k]"<< endl;
					cout << (int)pixelSubBuff[0]<< endl;					
					printf("%02d %02d %02d\n", i, j, h);					
				}
				
//				printf("%02d %02d %02d\n", i, j, h);
				serial->writeByte(h);				
				serial->writeBytes(pixelSubBuff, PIXELSUBSIZE);
				serial->writeByte(0xFE);
				
				ofSleepMillis(50);
//				cout << "ll";
				if(bLoop == false) break;
			}
			if(bLoop == false) break;
		}
	}
}

void ptclSendData::updateData(unsigned char* d)
{
	//stopSend();
	
	for(int i=0; i<PIXELSIZE*CHECKPOINTNUM; i++){
		pixelBuff[i] = d[i];
	}
//	cout << "in ptclSendData pixelBuff[0]"<< endl;
//	cout << (int)pixelBuff[0]<< endl;

	//startSend();
}


void ptclSendData::startSend()
{	
	bLoop = true;
	this->startThread(true, true);
}

void ptclSendData::stopSend()
{
	bLoop = false;
	ofSleepMillis(100);
	stopThread();
}

void ptclSendData::sendMaxColor(int tgtID, unsigned char r, unsigned char g, unsigned char b )
{
	//stopSend();
	unsigned char firstByte = ((r & 128) >> 7) | ((g & 128) >> 6) | ((b & 128) >> 5);
	unsigned char r1 = r & 127;
	unsigned char g1 = g & 127;
	unsigned char b1 = b & 127;
	
	serial->writeByte(0xFF);
	serial->writeByte(0xA6);
	serial->writeByte((unsigned char)tgtID);
	serial->writeByte(firstByte);
	serial->writeByte(r1);
	serial->writeByte(g1);
	serial->writeByte(b1);
	serial->writeByte(0xFE);
	
}

